package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CheckGroupService checkGroupService;

    @Autowired
    private CheckItemService checkItemService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Configuration configuration;


    private void generateMealListPage() throws Exception {

        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate("mobile_setmeal.ftl");//模板文件

        Map model = new HashMap<>();
        model.put("setmealList", setmealService.findAll());//填充数据

//        FileWriter out = new FileWriter("src/main/resources/mobile/pages/m_setmeal.html");
        FileWriter out = new FileWriter("D:/web/health/bxg-health-mobile/src/main/resources/mobile/pages/m_setmeal.html");
        template.process(model, out);
        out.close();

    }

    private void generateMealDetailPage(Integer mealId) throws Exception {

        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate("mobile_setmeal_detail.ftl");

        Map model = new HashMap<>();

        Setmeal setmeal = setmealService.findById(mealId);
        model.put("setmeal.img", setmeal.getImg());
        model.put("setmeal.name", setmeal.getName());
        model.put("setmeal.remark", setmeal.getRemark());
        model.put("setmeal.sex", setmeal.getSex());
        model.put("setmeal.age", setmeal.getAge());
        //套餐详情：检查组
        List<CheckGroup> checkgrouplist = checkGroupService.findCheckGroupBysetmealId(mealId);
        model.put("setmeal.checkGroups", checkgrouplist);
        //套餐详情：检查项
//        CheckGroup checkGroup = new CheckGroup();
        for (CheckGroup checkGroup : checkgrouplist) {
            Integer groupId = checkGroup.getId();
            List<CheckItem> checkItemlist = checkItemService.findCheckItemById(groupId);
            model.put("checkgroup.checkItems", checkItemlist);
        }

        FileWriter out = new FileWriter("D:/web/health/bxg-health-mobile/src/main/resources/static/meal_detail_" + mealId + ".html");
        template.process(model, out);
        out.close();

    }


    /**
     * 添加套餐信息
     *
     * @param setmeal
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgruopIds) throws Exception {
        log.info("添加套餐信息：{}", setmeal, checkgruopIds);
        setmealService.add(setmeal, checkgruopIds);
        //新增套餐成功后获取img地址，并缓存到redis中
        String savefile = setmeal.getImg();
        SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add("save", savefile);

        //重新生成静态页面
        generateMealListPage();
        generateMealDetailPage(setmeal.getId());

        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        log.info("分页查询：{}", queryPageBean);
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }

    /**
     * 查询套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id) {
        log.info("查询套餐信息：{}", id);
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
    }

//    /**
//     * 查询所有套餐信息
//     * @return
//     */
//    @GetMapping("/findAll")
//    public Result findAll(){
//        log.info("查询所有套餐信息");
//        List<Setmeal> setmeal = setmealService.findAll();
//        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
//    }

    /**
     * 修改套餐信息
     *
     * @param setmeal
     * @return
     */
    @PostMapping("/edit")
    public Result edit(Setmeal setmeal, Integer[] checkgruopIds) {
        log.info("修改套餐信息：{}", setmeal, checkgruopIds);
        setmealService.edit(setmeal, checkgruopIds);
        return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS);
    }

    /**
     * 删除套餐信息
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result delete(Integer id) {
        log.info("删除套餐信息：{}", id);
        setmealService.delete(id);
        return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS);
    }

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        log.info("图片上传：{}", imgFile);
        try {
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //截取原始文件名后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构建新的文件名称
            String newname = UUID.randomUUID().toString() + extension;

            //上传文件到阿里云
            Object filePath = aliOssUtil.upload(imgFile.getBytes(), newname);

            //获取上传的文件地址缓存到Redis的集合中
            SetOperations setOperations = redisTemplate.opsForSet();
            setOperations.add("save", filePath);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, filePath);
        } catch (IOException e) {
            log.info(MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }
}



